package cn.kgm.bio.threadUpload;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(6666);
        while (true) {
            // 在这里等待客户端链接，链接成功时会创建一个socket用于通信
            Socket socket = server.accept();
            new ServerReadThread(socket).start();
        }
    }

    private static class ServerReadThread extends Thread {
        Socket socket;

        ServerReadThread(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                DataInputStream dis = new DataInputStream(socket.getInputStream());
                String suffix = dis.readUTF();
                System.out.println("接收到的客户端文件类型： " + suffix);
                OutputStream os = new FileOutputStream("/Users/program/self/path2Java/netty/src/main/resources/niofile/" + UUID.randomUUID().toString() + suffix);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = dis.read(buffer)) >= 0) {
                    os.write(buffer, 0, len);
                }
                os.close();
                System.out.println("服务端保存数据成功！");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
